import { connect } from 'umi';
import React, { useEffect } from 'react';
import { Button, Select } from 'antd';

import { TRDefault } from '#/components';
import { useTRState } from '#/utils/trHooks.jsx';
import { PageLoading } from '@/components';
import { getTreeByCodes } from '@/utils/index.js';

import styles from './index.less';
import { queryMarketList } from './services';
import ElectricityPriceStatistics from './ElectEcharts';
import DemandSupplyAnalysis from './demandSupplyAnalysis';
import { HttpCode } from '#/utils/contacts';

const GenerQuantityPriceInfo = ({ menuCode, theme }) => {
  const [state, setState] = useTRState({
    error: '',
    power: [],
    stations: [],
    formValue: {},
    saveValue: {}, //查询后参数
    loading: true,
  });
  const { loading, error, power, stations, formValue, saveValue } = state;

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    setState({ loading: true });
    let error = '';
    let power = [];
    const res = await queryMarketList(menuCode);
    if (res?.statusCode === HttpCode.SUCCESS) {
      const { treeOptions } = getTreeByCodes(['market', 'station'], res.json);
      power = treeOptions;
      reset(power);
    } else {
      error = res?.message || '系统异常';
    }
    setState({
      error,
      power,
      loading: false,
    });
  };

  const reset = (data) => {
    const { provinceId, marketId, provinceName, stationName, children } = data[0] || power[0];
    const stationOptions = children;
    const stationId = stationOptions[0].value;
    const param = {
      provinceId,
      marketId,
      provinceName,
      stationId,
      stationName,
    };

    setState({
      formValue: param,
      saveValue: param,
      stations: stationOptions,
    });

    emitter.emit('onChangeUnit', stationId);
  };

  const renderHeader = () => {
    const { stationId, marketId } = formValue;
    return (
      <div className={styles.selectRow}>
        <Select
          value={marketId}
          options={power}
          allowClear={false}
          showSearch={true}
          style={{
            width: 200,
            margin: '14px 16px 14px 24px',
          }}
          onChange={(v, option) => {
            const stationOptions = option?.children;
            setState({
              formValue: {
                ...formValue,
                marketId: v,
                provinceId: option.provinceId,
                provinceName: option.provinceName,
                stationId: stationOptions[0]?.stationId,
                stationName: stationOptions[0]?.stationName,
              },
              stations: stationOptions,
            });
          }}
        />
        <Select
          showSearch={true}
          style={{
            width: 200,
            margin: '14px 16px 14px 0',
          }}
          options={stations}
          value={stationId}
          placeholder="请选择结算单元"
          filterOption={(inp, option) => option.label.includes(inp)}
          onChange={(value, opt) => {
            setState({
              formValue: {
                ...formValue,
                stationId: value,
                stationName: opt?.label,
              },
            });
          }}
        />

        <Button
          className={styles.search}
          type="primary"
          onClick={() => {
            setState({
              saveValue: formValue,
            });
            emitter.emit('onChangeUnit', stationId);
          }}
        >
          查询
        </Button>
        <Button onClick={reset} className={styles.search} type="ghost">
          重置
        </Button>
      </div>
    );
  };

  if (loading) return <PageLoading />;
  if (!power?.length) return <TRDefault type="lock" />;
  if (error) return <TRDefault type="error" message={error} />;

  return (
    <div className={styles.main}>
      <div className={styles.container}>
        {renderHeader()}
        <div className={styles.spot}>
          <ElectricityPriceStatistics
            stations={stations}
            title={'现货价格预测'}
            formValue={saveValue}
          />
        </div>
        <DemandSupplyAnalysis stations={stations} title={'全省供需分析'} formValue={saveValue} />
      </div>
    </div>
  );
};

export default connect(({ global }) => ({
  menuCode: global.configure.menuCode,
}))(GenerQuantityPriceInfo);
